/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.windfly.don.filter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import cn.windfly.don.DonConfig;
import cn.windfly.util.IOUtil;

/**
 * 请求耗时
 * 
 * @author Administrator
 */
@WebFilter(urlPatterns = { "*.dhtml" })
public class RequestLogFilter implements Filter {
	private boolean debug = DonConfig.getBoolean("don.debug");

	@Override
	public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (debug) {
			HttpServletRequest request = (HttpServletRequest) req;
			String params = "";
			if ("application/json".equalsIgnoreCase(request.getContentType())) {
				BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
				req = requestWrapper;
				params = new String(IOUtil.readAll(requestWrapper.getInputStream()),StandardCharsets.UTF_8);
			}else {
				params = request.getParameterMap().toString();
			}
			String str = 	
				"\n ========================================="
			+ "\n [Uri]:" + request.getRequestURI() 
			+ "\n [Params]:" + params
			+ "\n [Encoding]:" + request.getCharacterEncoding()
			+ "\n [ContentLength]:" + request.getContentLength()
			+ "\n [ContentType]:" + request.getContentType()
			+ "\n [RemoteAddr]:" + request.getRemoteAddr()
			+ "\n [ServletContext]:" + request.getServletContext()
			+ "\n [Accept]:" + request.getHeader("Accept")
			+ "\n [Content-Type]:" + request.getHeader("Content-Type")
			+ "\n [User-Agent]:" + request.getHeader("User-Agent")
			+ "\n =========================================";
			System.out.println(str);
			
		}
		chain.doFilter(req, response);
	}

	@Override
	public void destroy() {
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
}